import java.io.File;
import java.io.IOException;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;


public class SoundClip implements Runnable, IStreamSync {
	private Clip clip;
	
	public SoundClip(String file){
		
		try {
			File soundFile = new File(file);
			AudioInputStream sound = AudioSystem.getAudioInputStream(soundFile);
			
			//Load the sound
			DataLine.Info info = new DataLine.Info(Clip.class, sound.getFormat());
			clip = (Clip)AudioSystem.getLine(info);
			clip.open(sound);

		} catch (UnsupportedAudioFileException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (LineUnavailableException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			clip.close();
		}	
	}
	
	public void setPercentage(float p){
		//clip.stop();
		int frameIdx = (int)(clip.getFrameLength()*p);
		setFramePosition(frameIdx);
		//clip.start();
	}
	
	public float getPercentage(){
		return (float)clip.getFramePosition()/(float)clip.getFrameLength();
	}
	
	
	/********************************************
	 * Set the frame position, frame is zero-based
	 * @param time
	 */
	public void setFramePosition(int frames){
		clip.setFramePosition(frames);
	}
	
	/********************************************
	 * Set the time position, time is in milliseconds
	 * @param time
	 */
	public void setTimePosition(long milliseconds){
		int framePosition = (int)(milliseconds / 1000 * clip.getFormat().getSampleRate());
		setFramePosition(framePosition);
	}

	@Override
	public void start() {
		clip.start();
	}

	@Override
	public void pause() {
		clip.stop();
	}

	@Override
	public void stop() {
		clip.stop();
	}

	@Override
	public long getCurrentTimeStamp() {
		//return clip.getMicrosecondPosition()/1000;
		return (long)(1000 * clip.getLongFramePosition()/(double)clip.getFormat().getFrameRate());
	}

	@Override
	public void run() {
		clip.start();
	}
}
